import * as React from "react";
import { Form, Row, Col, Input, Button, Icon, DatePicker, Select, Table, message, Modal, Spin } from 'antd';
import * as moment from 'moment';
import './index.scss';
import { FormComponentProps } from 'antd/lib/form/Form' //获取form表单的interface
const { Option } = Select;
const { TextArea } = Input;
const { confirm } = Modal;
import Api from '../../config/api';
import { ListGUID } from '../../config/ListGuid';
import { number } from "echarts";
import { Prompt } from "react-router-dom";
import { isHavePermission, isHavePathPermission } from '../../utils/utils'
import { dynamicsService } from "../../../../../services/services";

// 检索
import { CAMLFilter, CAMLCompare, CamlQuery, SPDataType, CamlParam, CamlOrderBy } from './../../config/CAMLHelper';
const layout = {
  labelCol: {
    span: 4,

  },
  wrapperCol: {
    offset: 1,
    span: 19,
  },
}
const layoutS = {
  labelCol: {
    span: 6,

  },
  wrapperCol: {
    offset: 1,
    span: 17,
  },
}
const phoneValidator = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback('请输入！')
  }
  // 必须总是返回一个 callback，否则 validateFields 无法响应
  callback();
}
// 测试代码，调试API使用
class RegulationsVersion extends React.Component<any> {
  constructor(props: any & FormComponentProps) {
    super(props);
  }

  state = {
    AuthorId: JSON.parse(sessionStorage.getItem('userInfo')).Id,
    AuthorName: JSON.parse(sessionStorage.getItem('userInfo')).Title,
    currentForm: null,
    loading: false,
    regulationsId: '',
    backPage: '', // 返回的页面
    //表单数据对象
    form: {
      // 法务受理日
      date: null,
      // 法务最后回答日
      date1: null,
      // 语言
      language: null,
      // 规定名称
      theContract: null,
      // 规定编号
      otherSide: null,
      // 社内依赖者名
      community: null,
      // 其他
      other: null,
      // 法务审核编号
      contract: '',
      // 决裁编号
      cutNumber: '',
      // 审查担当
      reviewOn: null,
      // 文件保存
      file: null,
      //下拉选择
      //问题
      problem: undefined,
      //性质
      nature: undefined,
      //规定所属公司
      we: undefined,
      //修改性质
      qualifications: undefined,
      qualificationss: [],
      //律师审查
      examination: '无',
      //审查担当
      reviewOnxuan: [],
      //审查担当
      reviewOnxuans: undefined,
      //版本号
      versionNo: null,
      //申请书
      proposal:'无',

      //弹框
      contracts: '',
      reviewOns: null,
      theContracts: null,
      wes: undefined,
      enclosurelist: []
    },
    //问题
    problemList: [],
    //我方
    weList: [],
    //律师审查
    LawyerList: [],
    //审查担当
    personreviewList: [],
    //规定分类
    SpecifyList: [],
    //修改性质
    NatureList: [],
    //状态
    variable: '',
    //变量
    JudgmentVariable: null,
    JudgmentVariableID: number,

    //弹框
    visible: false,
    //数据
    datas: null,
    disabled: false,
    pidisabled: true,
    fujian: null,
    wedisabled: false,
    when: false
  }
  onBlurs(e) {
      let paten = /^[A-Za-z]+$/g;
      if(!paten.test(this.state.form.we)){
        message.warning('请输入字母',2);
        setTimeout(()=>{
          this.setState({
            form: {
              ...this.state.form,
              we : undefined,
            }
          })
          
          this.props.form.setFieldsValue({
            text: undefined,
          })
        },100)
        return;
      }
      
      this.props.form.setFieldsValue({
        text: this.state.form.we
      })
  }
  // 输入框改变赋值
  change(e, key) {
    
    if (key == 'we') {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e.target.value.toUpperCase()
        }
      })
    } else if (key == 'date' || key == 'date1') {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e.format('YYYY-MM-DD')
        }
      })
    } else {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e.target.value
        }
      })
    }
  }

  // 下拉框改变赋值
  handleSelectChange(e, key) {
    this.setState({
      form: {
        key: e,
        ...this.state.form,
        [key]: e
      }
    })
  }
  // 下拉框改变赋值
  handleSelectChanges(e, v, key) {
    var array = []
    var arrays = []
    v.forEach(element => {
      array.push(element.key)
      arrays.push(`${element.props.value}#${element.props.children}`)
    });
    this.setState({
      form: {
        ...this.state.form,
        reviewOn: array.join(","),
        reviewOnxuans: arrays.join(';'),
        [key]: e
      }
    })
  }
  // 下拉框改变赋值
  handleSelectChangess(e, v, key) {
    var array = []

    v.forEach(element => {
      array.push(element.key)
      // arrays.push(`${element.props.value}#${element.props.children}`)
    });
    
    let size = array.join(',')
    
    this.setState({
      form: {
        ...this.state.form,
        qualifications: array.join(","),
        [key]: e
      }
    })
    // 
  }
  //提交按钮触发
  submit = async (e) => {
    await this.setState({
      variable: e == '作废' ? '废弃' : e == '提交' ? '有效' : '草稿'
    })
    
    if (e == '作废') {
      let file = this.props.form.getFieldsValue(['file']).file
      let array = await Api.getFiles(ListGUID.RegulationsLibRelativeUrl + '/' + file)
      if (array.length != 0) {
        message.warning(`存在附件,请先删除附件`, 2)
        return;
      }
    }
    if (e == '保存草稿') {
      this.warning(e, this.props.form.getFieldsValue())
    } else {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          e == '提交' ? e = '保存' : e = e;
          this.warning(e, values)
        }
      });
    }

  };
  //提示框
  warning = (e, values) => {
    if(!this.state.currentForm && (e === '提交' || e === '保存')) {
      message.warning('请先匹配规章制度版本号再提交');
      return
    }
    confirm({
      centered: true,
      title: '温馨提示',
      content: `是否`+ e +`?`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => { this.getSubmit(e,values) }
    });
  };
  // 关闭按钮触发
  shutDown = async () => {
    let MinistryJustice = await Api._isLegalDepartment();
    confirm({
      centered: true,
      title: '温馨提示',
      content: `是否关闭该页面,关闭该页面未提交数据清空?`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // location.href = "#/Dashboard" 
        // 判断是否为法务部
        // MinistryJustice = false
        if (MinistryJustice) { location.href = "#/Dashboard"  } else {
          location.href = "#/DocumentLibrary"
        }
      }
    });
  };
  getFilds = () => {
    if (this.props.form.getFieldsValue(['file']).file) {
      // const filedom = document.getElementById('fileUploadInput');
      // filedom.click()
      dynamicsService.UpdateListFileNames({dataid: this.state.currentForm.id, listguid: ListGUID.Regulations, fileaddress: this.state.currentForm.FileAddress}).then(() => {
        if(isHavePermission('RegulationsVersion/todocumentlibrary')) {
          if(this.state.form.contract.indexOf('DUMY') === -1) {
            
            window.open(ListGUID.Domain + ListGUID.RegulationsLibRelativeUrl+'/'+this.props.form.getFieldsValue(['file']).file)
          } else {
            window.open(ListGUID.Domain + ListGUID.DumyLibRelativeUrl+'/'+this.props.form.getFieldsValue(['file']).file)
          }
          
        }
      })
      
      
      return;
    }
    message.warning('暂无上传路径', 2)
  }
  private setButtonsEventHandlers(): void {
    let fileUpload = document.getElementById('fileUploadInput');
    if (fileUpload) {
      fileUpload.addEventListener('change', () => {
        this.fileinputChange(fileUpload);
      });
    }
  }
  //循环
  getloop = async (item) => {
    var fileData = item;
    let fSize = fileData.size
    let fileName = fileData.name
    var maxSize = 20 * 1024 * 1024; //限制20M
    if (fSize > maxSize) {
      message.warning(`${fileName}文件内容太大，上传失败，请检查文件后重新上传!`, 2)
      return;
    }
    //判断空文件
    if (fSize == 0) {
      //空文件
      message.warning(`${fileName}的文件内容为空，请检查文件后重新上传!`, 2)
      return;
    }

    //判断文件名称合法
    if (fileName.indexOf('.') > -1 || fileName.indexOf('%') > -1 || fileName.indexOf('#') > -1 || fileName.indexOf('+') > -1) {
      //排除 .
      if (fileName.indexOf('.') > -1) {
        let firstCodePosition = fileName.indexOf('.');
        let lastCodePosition = fileName.lastIndexOf('.');
        if (firstCodePosition != lastCodePosition) {
          //位置不同，有多个 
          message.warning(`${fileName}文件名称包含特殊字符‘.’，不允许上传，请修改文件名称后重新上传`, 2)
          return;
        }
      }

      //排除 % # +
      if (fileName.indexOf('%') > -1 || fileName.indexOf('#') > -1 || fileName.indexOf('+') > -1) {
        message.warning(`${fileName}文件名称包含特殊字符‘%、#、+’，不允许上传，请修改文件名称后重新上传`, 2)
        return;
      }
    }

    //判断文件名称超长       
    if (fileName.length >= 44) {
      message.warning(`${fileName}文件名称超过40个字符，请修改文件名称后重新上传`, 2)
      return;
    }
    let file = this.props.form.getFieldsValue(['file']).file
    let array = await Api.getFiles(ListGUID.RegulationsLibRelativeUrl + '/' + file)
    if (array.length != 0) {
      for (let j = 0; j < array.length; j++) {
        if (fileName == array[j].Name) {
          message.warning(`${fileName}文件名已在申请中或文档中心已存在，请勿重复申请`, 2)
          return;
        }
      }
    }

    let url = ListGUID.RegulationsLibRelativeUrl + '/' + file
    let parme = Api._addfiles(fileData, url)
    if (parme) {
      var arrays = [];
      arrays.push(fileName)
      arrays = this.state.form.enclosurelist.concat(arrays)
      this.setState({
        form: {
          ...this.state.form,
          enclosurelist: arrays
        }
      })
      message.success(`${fileName}文件上传成功`, 2)
      
    }
  }
  //上传附件
  fileinputChange = async (event) => {
    for (let i = 0; i < event.files.length; i++) {
      this.getloop(event.files[i])
    }
  }
  //动态更新绑定数据
  public async componentDidMount() {
    isHavePathPermission()
    this.getTest();// 测试代码，调试API使用
    this.setState({
      AuthorId: JSON.parse(sessionStorage.getItem('userInfo')).Id,
      AuthorName: JSON.parse(sessionStorage.getItem('userInfo')).Title
    })
    let title = this.props.location.state
    if (title != undefined) {
      this.getedit(title.id)
      this.setState({
        regulationsId: title.id,
        backPage: title.backPage
      })
    }
    this.setButtonsEventHandlers()
  }
  public async componentDidUpdate(prevProps, prevState) {
    // let Container = JSON.parse(JSON.stringify(this.props.form.getFieldsValue()))
    // 
    // 
    // setTimeout(() => {
    //   if (Container.community == null || Container.community == "" && Container.contract == "" && Container.cutNumber == "" &&
    //     Container.date == null && Container.date1 == null && Container.examination == undefined &&
    //     Container.file == null && Container.language == null || Container.language == "" && Container.nature == undefined &&
    //     Container.other == null || Container.other == "" && Container.otherSide == null || Container.otherSide == "" && Container.problem == undefined &&
    //     Container.qualifications == undefined && Container.theContract == null || Container.theContract == "" && Container.versionNo == null &&
    //     Container.we == undefined || Container.we == ""
    //   ) {
    //     
    //     if (!this.state.when) return;
    //     let self = this;
    //     setTimeout(() => {
    //       self.setState({ when: false });
    //     })
    //   } else {
    //     
    //     if (this.state.when) return;
    //     let self = this;
    //     setTimeout(() => {
    //       self.setState({ when: true });
    //     })
    //   }
    // }, 1000)

  }
  //初始化数据
  initialization = () => {
    let { form } = this.state;
    form = {
      // 法务受理日
      date: null,
      // 法务最后回答日
      date1: null,
      // 语言
      language: null,
      // 规定名称
      theContract: null,
      // 规定编号
      otherSide: null,
      // 社内依赖者名
      community: null,
      // 其他
      other: null,
      // 法务审核编号
      contract: '',
      // 决裁编号
      cutNumber: '',
      // 审查担当
      reviewOn: null,
      // 文件保存
      file: null,
      //下拉选择
      //问题
      problem: undefined,
      //性质
      nature: undefined,
      //规定所属公司
      we: undefined,
      //修改性质
      qualifications: undefined,
      qualificationss: [],
      //律师审查
      examination: undefined,
      //审查担当
      reviewOnxuan: [],
      //审查担当
      reviewOnxuans: undefined,
      //版本号
      versionNo: null,
      //申请书
      proposal:undefined,

      //弹框
      contracts: '',
      reviewOns: null,
      theContracts: null,
      wes: undefined,
      enclosurelist: []

    }
    this.setState({
      form,
      disabled: false,
      wedisabled: false
    })
    this.props.form.resetFields()
  };
  //禁止选择年
  disabledDate = time => {
    if (this.state.wedisabled) {
      var timeYear = time.get('year');  //当前年
      var currentYear = moment(this.state.form.date).format('YYYY'); //今年
      return timeYear != currentYear;
    } else {
    }
  };
  //确定弹框
  handleOk = () => {

    this.setState({
      visible: false,
    });
  };
  //失去焦点
  onBlur = async () => {
    let yan = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*$/
    let contract = this.props.form.getFieldsValue(['contract']).contract
    if (contract.length > 10) {
      if (yan.test(contract)) {
        // var param1 = {
        //   Guid: ListGUID.Regulations, //台账
        //   Filter: `Title eq '${contract}-0' and RegulationsStatus eq '有效'`
        // };
        // let Person = await Api._getModel(param1);
        let params: any = [
          {
            logic: "and",
            where: [
              {
                key: 'Title',
                filterType: "Eq",
                value: `${contract}-0`
              },
              {
                key: 'RegulationsStatus',
                filterType: "Eq",
                value: `有效`
              }
            ]
          }
        ];
        let data = await Api._getPaged2({ Guid: ListGUID.Regulations, PageSize: 100000, PageIndex: 1, FilterL: params });
        let Person = data.data;
        if (Person.length != 0) {
          let { form } = this.state;
          form.contracts = Person[0].Title.substring(0, Person[0].Title.lastIndexOf('-'))
          form.reviewOns = Person[0].ReviewOn
          form.theContracts = Person[0].RegulationsName
          form.wes = Person[0].BelongsCompany

          this.setState({
            visible: true,
            datas: Person[0],
            form,
            pidisabled: false,
          })
        } else {
          message.warning('该编号没有查到采番数据或该编号已作废', 2)
        }
      } else {
        message.warning('请检查输入编号是否存在特殊符号!', 2)
      }
    } else {
      message.warning('请输入正确的编号!', 2)
    }
  }
  public render(): React.ReactElement {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className='box'>
        {/* <Prompt
            when={this.state.when}
            message={(location) =>
              "当前页面有未保存的内容,是否离开？"
            }
          /> */}
          <Spin spinning={this.state.loading}>
          <div className='box_content'>
          <Row align="middle" justify="end">
            <Col span={24}>
              <div className='flex'>
                <div className="heTong"></div>
                <div className='het'>规章制度版本号</div>
              </div>
            </Col>
          </Row>
          <Row type="flex" justify="end">
            {
                isHavePermission('RegulationsVersion/abandon') ? <Col span={1} > <Button type="default" className="Button_1" disabled={this.state.form.contract.indexOf('DUMY') !== -1  ? true : false} onClick={() => { this.submit("作废") }}>作废</Button></Col> : null
              }
            {
                isHavePermission('RegulationsVersion/submit') ? <Col span={1} offset={1}> <Button type="primary" className="Button_2" onClick={() => { this.submit("提交") }}>提交</Button></Col> : null
              }
            {
                isHavePermission('RegulationsVersion/draft') ? <Col span={1} offset={1}> <Button type="primary" className="Button_3"  disabled={this.state.form.contract && this.state.form.contract.indexOf('DUMY') === -1 ? true : false} onClick={() => { this.submit("保存草稿") }}>草稿</Button></Col> : null
              }
            {
                isHavePermission('RegulationsVersion/close') ? <Col span={1} offset={1}> <Button type="primary" onClick={this.shutDown}>关闭</Button></Col> : null
              }
              {
                this.state.regulationsId != '' ? <Col span={1} offset={1}> <Button type="primary" onClick={()=>{ this.props.history.push({pathname: this.state.backPage, state: {isBack: 1}}) }}>返回</Button>
              
            </Col> : ''
              }
            
          </Row>
          <div style={{ width: '100%', height: '20px' }}></div>
          <Form {...layout} name='login' layout="inline">
            <Row type="flex" align='middle'>
              <Col span={11}>
                <Form.Item label='法务审核编号' labelAlign="right">
                  {
                    getFieldDecorator('contract', {
                      rules: [
                        {
                          required: true
                        }
                      ],
                      initialValue: this.state.form.contract
                    })(<Input allowClear onBlur={this.onBlur} disabled={this.state.disabled} style={{ textTransform: 'uppercase' }}  placeholder='请输入'/>)
                  }
                </Form.Item>
              </Col>
              <Col span={2}>
                <Form.Item label='-N' className="FormItem ">
                  {
                    isHavePermission('RegulationsVersion/match') ? <Button type="primary" className="Button_3" onClick={this.generateNumber} disabled={this.state.pidisabled}>匹配</Button> : null
                  }

                </Form.Item>
              </Col>
              <Col span={11} offset={0}>
                <Form.Item label='问题' labelAlign="right">
                  {
                    getFieldDecorator('problem', {
                      initialValue: this.state.form.problem
                    })(<Select allowClear 
                      placeholder="请选择"
                      onChange={(event) => { this.handleSelectChange(event, "problem") }}
                    >
                      {
                        this.state.problemList.map(element => {
                          return <Option value={element.Title} key={element.ID}>{element.Title}</Option>
                        })
                      }
                    </Select>)
                  }
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item label='法务受理日' labelAlign="right">
                  {
                    getFieldDecorator('date', {
                      rules: [
                        {
                          required: true
                        }
                      ],
                      initialValue: this.state.form.date
                    })(<DatePicker allowClear  onChange={(event) => { this.change(event, "date") }} style={{ width: '100%' }} placeholder="请选择年份" format='YYYY/MM/DD'/>)
                  }

                </Form.Item>
              </Col>
              <Col span={11} offset={2}>
                <Form.Item label='规定分类' labelAlign="right">
                  {
                    getFieldDecorator('nature', {
                      initialValue: this.state.form.nature
                    })(<Select allowClear 
                      placeholder="请选择内容"
                      onChange={(event) => { this.handleSelectChange(event, "nature") }}
                    >
                      {
                        this.state.SpecifyList.map(element => {
                          return <Option value={element.Title} key={element.ID}>{element.Title}</Option>
                        })
                      }
                    </Select>)
                  }
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item label='法务最后回答日' labelAlign="right">
                  {
                    getFieldDecorator('date1', {
                      initialValue: this.state.form.date1
                    })(<DatePicker onChange={(event) => { this.change(event, "date1") }} allowClear  style={{ width: '100%' }} placeholder="请选择年份" format='YYYY/MM/DD' />)
                  }
                  {/* <DatePicker allowClear  value={this.state.form.date1 == null? this.state.form.date1 : moment(this.state.form.date1)} style={{ width: '100%' }} placeholder="请选择年份" onChange={this.onChange1} format='YYYY/MM/DD' /> */}
                  {/* <DatePicker allowClear  style={{ width: '100%' }} placeholder="请选择年份" /> */}
                </Form.Item>
              </Col>
              <Col span={11} offset={2}>
                <Form.Item label='修改性质' labelAlign="right">
                  {
                    getFieldDecorator('qualificationss', {
                      initialValue: this.state.form.qualificationss
                    })(<Select allowClear mode='multiple'
                      placeholder="请选择"
                      onChange={(event) => { this.handleSelectChange(event, "qualificationss") }}
                    >
                      {
                        this.state.NatureList.map(element => {
                          return <Option value={element.Title} key={element.ID}>{element.Title}</Option>
                        })
                      }
                    </Select>)
                  }
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item label='规定名称' labelAlign="right">
                  {
                    getFieldDecorator('theContract', {
                      rules: [
                        {
                          required: true
                        }
                      ],
                      initialValue: this.state.form.theContract
                    })(<Input allowClear onChange={(event) => { this.change(event, "theContract") }} style={{ width: '100%' }} placeholder="请输入名称" />)
                  }

                </Form.Item>
              </Col>


              <Col span={11} offset={2}>
                <Form.Item label='审核意见书' labelAlign="right">
                  <Select allowClear 
                    placeholder="请选择"
                    value={this.state.form.proposal}
                    onChange={(event) => { this.handleSelectChange(event, "proposal") }}
                  >
                     <Option value='有' >有</Option>
                     <Option value='无' >无</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item label='规定编号' labelAlign="right">
                  {
                    getFieldDecorator('otherSide', {
                      initialValue: this.state.form.otherSide
                    })(<Input allowClear onChange={(event) => { this.change(event, "otherSide") }} style={{ width: '100%' }} placeholder="请输入" />)
                  }

                </Form.Item>
              </Col>
              <Col span={11} offset={2}>
                <Form.Item label='律师审查' labelAlign="right">
                  {
                    getFieldDecorator("examination", {
                      initialValue: this.state.form.examination
                    })(<Select allowClear 
                      placeholder="请选择"
                      onChange={(event) => { this.handleSelectChange(event, "examination") }}
                    >
                      {
                        this.state.LawyerList.map(element => {
                          return <Option value={element.ID} key={element.ID}>{element.Title}</Option>
                        })
                      }
                    </Select>)
                  }
                </Form.Item>
              </Col>
              


              <Col span={11}  >
                <Form.Item label='版本号' labelAlign="right">
                  {
                    getFieldDecorator('versionNo', {
                      initialValue: this.state.form.versionNo
                    })(<Input allowClear  onChange={(event) => { this.change(event, "versionNo") }} style={{ width: '100%' }} placeholder="请输入" />)
                  }
                  {/* <Input allowClear style={{ width: '100%' }} placeholder="请输入" /> */}
                </Form.Item>
                
              </Col>
              <Col span={11} offset={2}>
                <Form.Item label='其他' labelAlign="right">
                  {
                    getFieldDecorator('other', {
                      initialValue: this.state.form.other
                    })(<Input allowClear onChange={(event) => { this.change(event, "other") }} placeholder="请输入内容" style={{ width: '100%' }} />)
                  }
                  {/* <TextArea rows={4} placeholder="请输入" maxLength={99} style={{ width: '100%' }}
                    value={this.state.form.other} onChange={(event) => { this.change(event, "other") }} /> */}
                </Form.Item>
              </Col>
              
              <Col span={11}>
                <Form.Item label='规定所属公司' labelAlign="right">
                  {
                    getFieldDecorator('we', {
                      rules: [
                        {
                          required: true
                        }
                      ],
                      initialValue: this.state.form.we
                    })(
                      <Select allowClear 
                      onChange={(event) => { this.handleSelectChange(event, "we") }}
                      disabled= {this.state.currentForm && this.state.form.contract.indexOf('DUMY') === -1 ? true: false}
                      placeholder="请选择"
                    >
                      {
                        this.state.weList.map(element => {
                          return <Option value={element.Title} key={element.Title}>{element.Title}</Option>
                        })
                      }
                    </Select>
                    //<Input allowClear placeholder="请输入内容" onBlur={(event) => { this.onBlurs(event) }} style={{ textTransform: 'uppercase' }} onChange={(event) => { this.change(event, "we") }} disabled={this.state.wedisabled} />
                    )
                  }
                </Form.Item>
              </Col>
              <Col span={11} offset={2}>
                <Form.Item label='决裁编号' labelAlign="right">
                  {
                    getFieldDecorator('cutNumber', {
                      initialValue: this.state.form.cutNumber
                    })(<Input allowClear style={{ width: '100%' }} placeholder="请输入" disabled />)
                  }
                </Form.Item>
              </Col>
             

              <Col span={11}>
                <Form.Item label='依赖者名' labelAlign="right">
                  {
                    getFieldDecorator('community', {
                      initialValue: this.state.form.community
                    })(<Input onChange={(event) => { this.change(event, "community") }} allowClear style={{ width: '100%' }} placeholder="请输入" />)
                  }
                  {/* <Input allowClear style={{ width: '100%' }} placeholder="请输入" /> */}
                </Form.Item>
              </Col>
              <Col span={11} offset={2}>
                <Form.Item label="审查担当" >
                  <Input.Group compact>
                    <Select allowClear  mode='multiple' placeholder="请选择" style={{ width: '35%' }} value={this.state.form.reviewOnxuan}
                      onChange={(event, value) => { this.handleSelectChanges(event, value, "reviewOnxuan") }} maxTagCount={1}>
                      {
                        this.state.personreviewList.map(element => {
                          return <Option value={element.ID} key={element.Title}>{element.Title}</Option>
                        })
                      }
                    </Select>
                    <Input allowClear style={{ width: '65%' }}
                      placeholder="请输入内容" disabled value={this.state.form.reviewOn} />
                  </Input.Group>
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item label='语言' labelAlign="right">
                  {
                    getFieldDecorator('language', {
                      initialValue: this.state.form.language
                    })(<Input onChange={(event) => { this.change(event, "language") }} allowClear placeholder="请输入内容" />)
                  }
                  {/* <Input allowClear placeholder="请输入内容" value={this.state.form.language} onChange={(event) => { this.change(event, "language") }}/> */}
                </Form.Item>
              </Col>
              <Col span={11} offset={2}>
                <Form.Item label='文件保存' labelAlign="right">
                  {
                    getFieldDecorator('file', {
                      initialValue: this.state.form.file
                    })(<Input allowClear onClick={this.getFilds} readOnly />)
                  }
                  {
                    isHavePermission('RegulationsVersion/upload') ? <Input allowClear placeholder="附件" multiple value={this.state.fujian} id="fileUploadInput" type="file" name="myfile" style={{ display: "none" }} /> : null
                  }

                </Form.Item>
              </Col>
              
            </Row>
          </Form>
          <Modal
            title="合同版本号采番"
            destroyOnClose={true}
            visible={this.state.visible}
            centered={true}
            closable={false}
            footer={null}

          >
            <Form {...layoutS} className="Formitems">
              <Row>
                <Col span={20}>
                  <Form.Item label='法务审核编号' labelAlign="right" className="chehsi" style={{ margin: 0 }}>
                    <Input allowClear style={{ width: '65%' }} value={this.state.form.contracts} disabled  placeholder="请输入"/>
                    <span>-N</span>
                  </Form.Item>
                </Col>
                <Col span={20}>
                  <Form.Item label='规定名称' labelAlign="right" className="chehsi" style={{ margin: 0 }}>
                    <Input allowClear value={this.state.form.theContracts} disabled />
                  </Form.Item>
                </Col>
                <Col span={20}>
                  <Form.Item label='规定所属公司' labelAlign="right" className="chehsi" style={{ margin: 0 }}>
                    <Input allowClear value={this.state.form.wes} disabled />
                  </Form.Item>
                </Col>
                <Col span={20}>
                  <Form.Item label='审查担当' labelAlign="right">
                    <Input allowClear value={this.state.form.reviewOns} disabled />
                  </Form.Item>
                </Col>
                <Col span={5} offset={19}>
                  <Form.Item>
                    <Button type="primary" style={{ padding: ' 0 24px' }} onClick={() => {
                      this.setState({
                        visible: false
                      })
                    }}>关闭</Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>

          </Modal>
        </div>
          </Spin>
        
      </div>
    )

  }
  //合同性质 合同期限 合同重要性 律师审查 审查担当  公司设置  问题 部门列表
  //访问list NaturcontractGUID,ContractperiodGUID,ContractimportanceGUID,LawyerreviewGUID,PersonGUID,CompanysettingsGUID,ProblemGUID,DepartmentlstGUID
  public async getTest() {

    var param7 = {
      Guid: ListGUID.ReviewOn //审查担当
    };
    let Person = await Api._getModel(param7);
    var param1 = {
      Guid: ListGUID.ReviseNature //修改性质
    }

    let Nature = await Api._getModel(param1);
    var param2 = {
      Guid: ListGUID.RegulationsType //规定分类
    }

    let Specify = await Api._getModel(param2);

    var param3 = {
      Guid: ListGUID.LawerReview //律师审查
    };
    let Lawyerreview = await Api._getModel(param3);

    var param5 = {
      Guid: ListGUID.Question // 问题 
    };
    let Problem = await Api._getModel(param5);
    var param4 = {
      Guid: ListGUID.Companies // 公司设置
    };
    let Companysettings = await Api._getModel(param4);
    // let Companysettings = JSON.parse(sessionStorage.getItem('userDataPer')).PermissionCompany
    const userList = JSON.parse(localStorage.getItem('usersList'));
    Person = !this.state.regulationsId ? Person.filter(i => !i.Title.includes('-历史')) : Person
    Person.forEach(async item => {
      // let informationid = await Api.GetUserById(item.ReviewUserId)
      let informationid = userList.filter(i => i.id === item.ReviewUserId)
      if (informationid && informationid.length > 0) {
        item.Title = informationid.Title
      }
      
      return
    });
    setTimeout(() => {
      this.setState({
        //规定分类
        SpecifyList: Specify,
        //修改性质
        NatureList: Nature,
        LawyerList: Lawyerreview,
        problemList: Problem,
        personreviewList: Person,
        weList: Companysettings.filter(i => !i.Title.includes('-历史')),
      }, () => {
        if(!this.state.currentForm) {
          this.getcurrentUser()
        }
      })
    }, 300)
    // _that.state.problemList = Departmentlst

  }
  //默认登陆人
  public async getcurrentUser() {
    
    let { form } = this.state;
    //获取当前登录人
    let Loggedby = await Api._getcurrentUser();
    this.state.personreviewList.forEach(element => {
      if (Loggedby.Id === element.ReviewUserId) {
        form.reviewOnxuan = []
        form.reviewOnxuan.push(element.Id)
        form.reviewOn = element.Title
        form.reviewOnxuans = `${element.Id}#${element.Title}`
      }
    });
    this.setState({
      form
    })
    

  }
  //提交
  public async getSubmit(e,values) {
    if(this.state.currentForm) {
      this.UpdateData(this.state.currentForm.ItemId)
    } else {
      if(e === '提交' || e === '保存') {
        message.warning('请先匹配规章制度版本号再提交');
        return
      }
      if(this.state.variable === '草稿') {
        this.AddData()
      }
    }
    /** ---------------------------  先注释掉 */
    
    // var MinistryJustice = await Api._isLegalDepartment();
    // var date = new Dated
    // var year = date.getFullYear();
    // 
    // var param = {
    //   Guid: ListGUID.Regulations, //台账
    //   Filter: `Title eq '${values.contract}'`
    // };
    // let Person = await Api._getModel(param);
    // if (Person.length != 0) {
    //   //  添加新合同
    //   var pa = {
    //     Guid: ListGUID.Regulations,  //变更申请
    //     ItemId: Person[0].ID,
    //     Obj: {
    //       Title: values.contract, //合同编号
    //       AcceptTime: values.date ? moment(values.date).format('YYYY-MM-DD') : null,//法务受理日
    //       Language: values.language,//语言
    //       Question: values.problem,//问题
    //       LastAnswerTime: values.date1 ? moment(values.date1).format('YYYY-MM-DD') : null,//法务最后回答
    //       RegulationsCatalog: values.nature,  //规定分类
    //       RegulationsName: values.theContract,  //规定名称
    //       ModifyNature: values.qualifications, //修改性质
    //       RegulationsNum: values.otherSide, //规定编号
    //       LawyerReview: values.examination,//律师审查
    //       BelongsCompany: values.we, //规定所属公司
    //       RuleNumber: values.cutNumber,//决裁编号
    //       RelierName: values.community,//社内依赖者
    //       ReviewOn: this.state.form.reviewOnxuans,//审查担当
    //       Other: values.other,//其它 
    //       HasReviewOpinion:this.state.form.proposal,//申请书
    //       SerialNum: values.contract ? Number(values.contract.substring(0, values.contract.lastIndexOf('-')).substr(-3)) : null, //流水号
    //       AcceptYear: values.date ? Number(moment(values.date).format('YYYY-MM-DD').substring(0, 4)) : null,//受理日年份
    //       VersionNum: values.versionNo ? Number(values.versionNo) : undefined,// 版本号
    //       RegulationsStatus: this.state.variable,//状态
    //       FileAddress: values.file,//文件保存路径
    //       Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';')
    //     }
    //   };
    //   //废弃编号启用
    //   if (this.state.JudgmentVariable == '废弃') {
    //     if (this.state.variable == '草稿') {
    //       var param = {
    //         Guid: ListGUID.Regulations, //台账
    //         Filter: `RegulationsStatus eq '草稿'`
    //       };
    //       let Persons = await Api._getModel(param);
    //       if (Persons.length != 0) {
    //         let array = []
    //         Persons.forEach(element => {
    //           array.push({
    //             Title: Number(element.Title.substr(-3)),
    //             conter: element.Title.slice(0, element.Title.length - 3),
    //             ID: element.ID
    //           })
    //         });
    //         array.sort(function (a, b) {
    //           return a.Title - b.Title  //正序
    //         })
    //         pa.Obj.Title = array[array.length - 1].conter + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3)
    //         pa.Obj.AcceptYear = Number(year)
    //       } else {
    //         pa.Obj.Title = 'DUMY' + Number(year) + "001"
    //         pa.Obj.AcceptYear = Number(year)
    //       }

    //     }
    //     let parm = {
    //       Guid: pa.Guid,
    //       ItemId: Number(this.state.JudgmentVariableID),
    //       Obj: pa.Obj
    //     }

    //     var UPdeta = await Api._updateData(parm)
    //     this.initialization()
    //     if (MinistryJustice) { location.href = "#/Dashboard"  } else {
    //       location.href = "#/DocumentLibrary"
    //     }
    //     return;
    //   }
    //   if (this.state.variable == '草稿') {
    //     var param = {
    //       Guid: ListGUID.Regulations, //台账
    //       Filter: `RegulationsStatus eq '草稿'`
    //     };
    //     let Persons = await Api._getModel(param);
    //     if (Persons.length != 0) {
    //       let array = []
    //       Persons.forEach(element => {
    //         array.push({
    //           Title: Number(element.Title.substr(-3)),
    //           conter: element.Title.slice(0, element.Title.length - 3),
    //           ID: element.ID
    //         })
    //       });
    //       array.sort(function (a, b) {
    //         return a.Title - b.Title  //正序
    //       })
    //       pa.Obj.Title = array[array.length - 1].conter + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3)
    //       pa.Obj.AcceptYear = Number(year)
    //     } else {
    //       pa.Obj.Title = 'DUMY' + Number(year) + "001"
    //       pa.Obj.AcceptYear = Number(year)
    //     }

    //   }
    //   var result = await Api._updateData(pa);
    //   this.initialization()
    //   if (MinistryJustice) { location.href = "#/Dashboard"  } else {
    //     location.href = "#/DocumentLibrary"
    //   }
    // } else {
    //   var content = {
    //     Guid: ListGUID.Regulations,  //变更申请
    //     Obj: {
    //       Title: values.contract, //合同编号
    //       AcceptTime: values.date ? moment(values.date).format('YYYY-MM-DD') : null,//法务受理日
    //       Language: values.language,//语言
    //       Question: values.problem,//问题
    //       LastAnswerTime: values.date1 ? moment(values.date1).format('YYYY-MM-DD') : null,//法务最后回答
    //       RegulationsCatalog: values.nature,  //规定分类
    //       RegulationsName: values.theContract,  //规定名称
    //       ModifyNature: values.qualifications, //修改性质
    //       RegulationsNum: values.otherSide, //规定编号
    //       LawyerReview: values.examination,//律师审查
    //       BelongsCompany: values.we, //规定所属公司
    //       RuleNumber: values.cutNumber,//决裁编号
    //       RelierName: values.community,//社内依赖者
    //       ReviewOn: this.state.form.reviewOnxuans,//审查担当
    //       Other: values.other,//其它 
    //       HasReviewOpinion:this.state.form.proposal,//申请书
    //       SerialNum: values.contract ? Number(values.contract.substring(0, values.contract.lastIndexOf('-')).substr(-3)) : null, //流水号
    //       AcceptYear: values.date ? Number(moment(values.date).format('YYYY-MM-DD').substring(0, 4)) : null,//受理日年份
    //       VersionNum: values.versionNo ? Number(values.versionNo) : undefined,// 版本号
    //       RegulationsStatus: this.state.variable,//状态
    //       FileAddress: values.file,//文件保存路径
    //       Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';')
    //     }
    //   };
    //   if (this.state.variable == '草稿') {
    //     var param = {
    //       Guid: ListGUID.Regulations, //台账
    //       Filter: `RegulationsStatus eq '草稿'`
    //     };
    //     let Persons = await Api._getModel(param);
    //     if (Persons.length != 0) {
    //       let array = []
    //       Persons.forEach(element => {
    //         array.push({
    //           Title: Number(element.Title.substr(-3)),
    //           conter: element.Title.slice(0, element.Title.length - 3),
    //           ID: element.ID
    //         })
    //       });
    //       array.sort(function (a, b) {
    //         return a.Title - b.Title  //正序
    //       })
    //       content.Obj.Title = array[array.length - 1].conter + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3)
    //       content.Obj.AcceptYear = Number(year)
    //     } else {
    //       content.Obj.Title = 'DUMY' + Number(year) + "001"
    //       content.Obj.AcceptYear = Number(year)
    //     }

    //   }
    //   
    //   var result = await Api._saveaddDataGuid(content);
    //   this.initialization()
    //   if (MinistryJustice) { location.href = "#/Dashboard"  } else {
    //     location.href = "#/DocumentLibrary"
    //   }
    // }
    /**--------------------- */
  }
  // 更新数据
  UpdateData = async (id) => {
    
    this.setState({
      loading: true
    })
    let parm = {
      Guid: ListGUID.Regulations,
      ItemId: id,
      Obj: {
        Title: this.state.form.contract, //合同编号
        AcceptTime: this.state.form.date ? moment(this.state.form.date).format('YYYY-MM-DD') : null,//法务受理日
        Language: this.state.form.language,//语言
        Question: this.state.form.problem,//问题
        LastAnswerTime: this.state.form.date1 ? moment(this.state.form.date1).format('YYYY-MM-DD') : null,//法务最后回答
        RegulationsCatalog: this.state.form.nature,  //规定分类
        RegulationsName: this.state.form.theContract,  //规定名称
        ModifyNature: this.state.form.qualificationss && this.state.form.qualificationss.join(','), //修改性质
        RegulationsNum: this.state.form.otherSide, //规定编号
        LawyerReview: this.state.form.examination,//律师审查
        BelongsCompany: this.state.form.we, //规定所属公司
        RuleNumber: this.state.form.cutNumber,//决裁编号
        RelierName: this.state.form.community,//社内依赖者
        ReviewOn: this.state.form.reviewOnxuans,//审查担当
        Other: this.state.form.other,//其它 
        HasReviewOpinion:this.state.form.proposal,//申请书
        SerialNum: this.state.form.contract ? Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)) : null, //流水号
        AcceptYear: this.state.form.date ? Number(moment(this.state.form.date).format('YYYY-MM-DD').substring(0, 4)) : null,//受理日年份
        VersionNum: this.state.form.versionNo,// 版本号
        RegulationsStatus: this.state.variable || '有效',//状态
        // FileAddress: this.state.form.file,//文件保存路径
        // Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';')
      }
    }
    // await Api._updateData(parm)
    parm.Obj['AuthorName'] = this.state.AuthorName;
    parm.Obj['ItemId'] = id;
    let response = await dynamicsService.UpdateRegulation(parm.Obj)
    if(response.code === 200) {
      let reviewOnxuan = []
      let reviewOn = []
      if (response.data.ReviewOn != null) {
        if (response.data.ReviewOn.indexOf(';') != -1) {
          let arrays = response.data.ReviewOn.split(';')
          for (let i = 0; arrays.length > i; i++) {
            reviewOnxuan.push(Number(arrays[i].split('#')[0]))
            reviewOn.push(arrays[i].split('#')[1])
          }
        } else {
          reviewOnxuan.push(Number(response.data.ReviewOn.split('#')[0]))
          reviewOn.push(response.data.ReviewOn.split('#')[1])
        }
      }
      let form = {
        contract: response.data.Title, //合同编号
        date: response.data.AcceptTime == null ? null : moment(response.data.AcceptTime),
        date1: response.data.LastAnswerTime == null ? null : moment(response.data.LastAnswerTime),
        language: response.data.Language,//语言
        problem: response.data.Question,//问题
        nature: response.data.RegulationsCatalog,//规定分类
        theContract: response.data.RegulationsName,//规定名称
        qualificationss: response.data.ModifyNature ? response.data.ModifyNature.split(',') : [],//修改性质
        otherSide: response.data.RegulationsNum,//规定编号
        examination: response.data.LawyerReview || '无',//律师审查 
        we: response.data.BelongsCompany, //规定所属公司
        cutNumber: response.data.RuleNumber,//决裁编号
        community: response.data.RelierName,//社内依赖者
        reviewOnxuans: response.data.ReviewOn,//审查担当
        file: response.data.FileAddress,//文件保存路径
        other: response.data.Other,//其它 
        proposal:response.data.HasReviewOpinion || '无',//申请书
        reviewOnxuan: reviewOnxuan,
        reviewOn: reviewOn,
        versionNo: response.data.VersionNum,
        contracts: response.data.Title.substring(0, response.data.Title.lastIndexOf('-'))
      }
    this.props.form.setFieldsValue({
      contract: response.title
    })
    this.setState({
      currentForm: response.data
    })
    this.setState({
      form,
      reviewOnxuan,
      reviewOn,
      loading: false
    })
    } else {
      this.setState({
        loading: false
      })
      message.warning(response.msg)
    }
    
  }
  // 新增数据
  AddData = async () => {
    
    this.setState({
      loading: true
    })
    let parm = {
      Guid: ListGUID.Regulations,
      Obj: {
        Title: this.state.form.contracts, //合同编号
        AcceptTime: this.state.form.date ? moment(this.state.form.date).format('YYYY-MM-DD') : null,//法务受理日
        Language: this.state.form.language,//语言
        Question: this.state.form.problem,//问题
        LastAnswerTime: this.state.form.date1 ? moment(this.state.form.date1).format('YYYY-MM-DD') : null,//法务最后回答
        RegulationsCatalog: this.state.form.nature,  //规定分类
        RegulationsName: this.state.form.theContract,  //规定名称
        ModifyNature: this.state.form.qualificationss ? this.state.form.qualificationss.join(',') : '', //修改性质
        RegulationsNum: this.state.form.otherSide, //规定编号
        LawyerReview: this.state.form.examination,//律师审查
        BelongsCompany: this.state.form.we, //规定所属公司
        RuleNumber: this.state.form.cutNumber,//决裁编号
        RelierName: this.state.form.community,//社内依赖者
        ReviewOn: this.state.form.reviewOnxuans,//审查担当
        Other: this.state.form.other,//其它 
        HasReviewOpinion:this.state.form.proposal,//申请书
        SerialNum: this.state.form.contract ? Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)) : null, //流水号
        AcceptYear: this.state.form.date ? Number(moment(this.state.form.date).format('YYYY-MM-DD').substring(0, 4)) : null,//受理日年份
        VersionNum: this.state.form.versionNo,// 版本号
        RegulationsStatus: this.state.variable || '有效',//状态
        // Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';')
      }
    }
    parm.Obj['AuthorId'] = this.state.AuthorId;
    parm.Obj['AuthorName'] = this.state.AuthorName;
    let response = await dynamicsService.AddRegulation(parm.Obj)
    if(response.code === 200) {
      // if(response.ItemId) {
      //   this.UpdateData(response.ItemId)
      // } else {
      //   // let UPdeta = await Api._saveaddDataGuid(parm);
      //   // let { form } = this.state;
      //   // form.file = this.state.form.date.substring(0, 4) + '/' + this.state.form.we + '/' + this.state.form.contract + '/';
      //   // form.examination = '无'
      //   // form.proposal = '无'
      //   // this.Folder(this.state.form.we, this.state.form.date.substring(0, 4), this.state.form.contract)
      //   this.setState({
      //     form: response.data,
      //     JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '有效'
      //   })
      // }
      let reviewOnxuan = []
      let reviewOn = []
      if (response.data.ReviewOn != null) {
        if (response.data.ReviewOn.indexOf(';') != -1) {
          let arrays = response.data.ReviewOn.split(';')
          for (let i = 0; arrays.length > i; i++) {
            reviewOnxuan.push(Number(arrays[i].split('#')[0]))
            reviewOn.push(arrays[i].split('#')[1])
          }
        } else {
          reviewOnxuan.push(Number(response.data.ReviewOn.split('#')[0]))
          reviewOn.push(response.data.ReviewOn.split('#')[1])
        }
      }
      let form = {
        contract: response.data.Title, //合同编号
        date: response.data.AcceptTime == null ? null : moment(response.data.AcceptTime),
        date1: response.data.LastAnswerTime == null ? null : moment(response.data.LastAnswerTime),
        language: response.data.Language,//语言
        problem: response.data.Question,//问题
        nature: response.data.RegulationsCatalog,//规定分类
        theContract: response.data.RegulationsName,//规定名称
        qualificationss: response.data.ModifyNature ? response.data.ModifyNature.split(',') : [],//修改性质
        otherSide: response.data.RegulationsNum,//规定编号
        examination: response.data.LawyerReview || '无',//律师审查 
        we: response.data.BelongsCompany, //规定所属公司
        cutNumber: response.data.RuleNumber,//决裁编号
        community: response.data.RelierName,//社内依赖者
        reviewOnxuans: response.data.ReviewOn,//审查担当
        file: response.data.FileAddress,//文件保存路径
        other: response.data.Other,//其它 
        proposal:response.data.HasReviewOpinion || '无',//申请书
        reviewOnxuan: reviewOnxuan,
        reviewOn: reviewOn,
        versionNo: response.data.VersionNum,
        contracts: response.data.Title.substring(0, response.data.Title.lastIndexOf('-'))
      }
      this.setState({
        form: form,
        reviewOnxuan,
        reviewOn,
        JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '有效',
        loading: false
      })
      this.props.form.setFieldsValue({
        contract: response.title
      })
      this.setState({
        currentForm: response.data
      })
    } else {
      this.setState({
        loading: false
      })
      message.warning(response.msg);
    }
    
  }
  //生成编号
  private generateNumber = async (e) => {
    this.setState({
      variable: '有效'
    }, () => {
      e.preventDefault();
    this.props.form.validateFields(['contract'], async (err, values) => {
      if (!err) {
        if(this.state.currentForm) {
          if(this.state.currentForm.Title) {
            this.AddData()
          } else {
            this.UpdateData(this.state.currentForm.ItemId)
          }
          
        } else {
          this.AddData()
        }
        /** ------------------------------------------ 暂时注释 */
        // let params= []
        // params.push(new CamlParam("Title",this.state.form.contracts, SPDataType.Text, CAMLCompare.Contains));
        // params.push(new CamlParam("RegulationsStatus", '废弃', SPDataType.Text, CAMLCompare.Eq));
        // params.push(new CamlParam("VersionNum", '0', SPDataType.Number, CAMLCompare.Neq));
        // let camlQuery = {
        //   ViewXml: ''
        // }
        // //不排序
        // let demo = Api.buildCamlXml(params);
        // let Guid = ListGUID.Regulations //根据条件检索表数据
        // camlQuery.ViewXml = demo
        // let Persons = await Api.GetListItemsByCAMLQuery(Guid, camlQuery);
        // 
        // // var param = {
        // //   Guid: ListGUID.Regulations, //guid 规章
        // //   Filter: `substringof('${this.state.form.contracts}',Title) and  RegulationsStatus eq '废弃'`
        // // };
        // // let Persons = await Api._getModel(param);

        // if (Persons.length != 0) {
        //   let array = []
        //   Persons.forEach(element => {
        //     array.push({
        //       Titles: element.Title,
        //       FileAddress: element.FileAddress,
        //       Title: Number(element.Title.split('-')[1]),
        //       ID: element.ID
        //     })
        //   });
        //   array.sort(function (a, b) {
        //     return a.Title - b.Title  //正序
        //   })
        //   //获取废弃的编号
        //   let { form } = this.state;
        //   let reviewOnxuan = []
        //   let reviewOn = []
        //   if (this.state.datas.ReviewOn != null) {
        //     if (this.state.datas.ReviewOn.indexOf(';') != -1) {
        //       let arrays = this.state.datas.ReviewOn.split(';')
        //       for (let i = 0; arrays.length > i; i++) {
        //         reviewOnxuan.push(Number(arrays[i].split('#')[0]))
        //         reviewOn.push(arrays[i].split('#')[1])
        //       }
        //     } else {
        //       reviewOnxuan.push(Number(this.state.datas.ReviewOn.split('#')[0]))
        //       reviewOn.push(this.state.datas.ReviewOn.split('#')[1])
        //     }
        //   }
        //   form.reviewOnxuan = reviewOnxuan
        //   form.reviewOn = reviewOn
        //   form.proposal = '无'
        //   form.reviewOnxuans = this.state.datas.ReviewOn

        //   this.props.form.setFieldsValue({
        //     contract: array[0].Titles, //编号
        //     theContract: this.state.datas.RegulationsName,//名称
        //     qualifications: this.state.datas.ModifyNature,//修改性质
        //     we: this.state.datas.BelongsCompany,//我方
        //     examination: this.state.datas.LawyerReview,//律师审查
        //     file: array[0].FileAddress,//文件保存
        //     reviewOnxuans: this.state.datas.ReviewOn,//审查担当
        //     versionNo: Number(array[0].Titles.split('-')[1])
        //   });

        //   setTimeout(() => {
        //     this.Folder(this.state.datas.BelongsCompany, this.state.datas.AcceptTime.substring(0, 4), this.state.form.contracts + '-' + (Number(array[0].Title)))
        //     this.setState({
        //       form,
        //       disabled: true,
        //       pidisabled:true,
        //       JudgmentVariableID: this.state.wedisabled ? this.state.JudgmentVariableID : array[0].ID,
        //       JudgmentVariable: this.state.wedisabled ? this.state.JudgmentVariable : '废弃'
        //     })
        //   }, 100);

        //   return;
        // }
        // let param= []
        // param.push(new CamlParam("Title",this.state.form.contracts, SPDataType.Text, CAMLCompare.Contains));
        // param.push(new CamlParam("RegulationsStatus", '有效', SPDataType.Text, CAMLCompare.Eq));
        // let camlQuerys = {
        //   ViewXml: ''
        // }
        // //不排序
        // let demos = Api.buildCamlXml(param);
        // let Guids = ListGUID.Regulations //根据条件检索表数据
        // camlQuerys.ViewXml = demos
        // let Person = await Api.GetListItemsByCAMLQuery(Guids, camlQuerys);
        // 
        // // var param1 = {
        // //   Guid: ListGUID.Regulations, //guid 规章
        // //   Filter: `substringof('${this.state.form.contracts}',Title) and  RegulationsStatus eq '有效'`
        // // };
        // // let Person = await Api._getModel(param1);
        // if (Person.length != 0) {
        //   let array = []
        //   Person.forEach(element => {
        //     array.push({
        //       Title: Number(element.Title.split('-')[1]),
        //       ID: element.ID
        //     })
        //   });
        //   array.sort(function (a, b) {
        //     return a.Title - b.Title  //正序
        //   })
        //   let { form } = this.state;
        //   let reviewOnxuan = []
        //   let reviewOn = []
        //   if (this.state.datas.ReviewOn) {
        //     let arrays = this.state.datas.ReviewOn.split(';')
        //     for (let i = 0; arrays.length > i; i++) {
        //       reviewOnxuan.push(Number(arrays[i].split('#')[0]))
        //       reviewOn.push(arrays[i].split('#')[1])
        //     }
        //   }
        //   form.reviewOnxuan = reviewOnxuan
        //   form.reviewOn = reviewOn
        //   form.proposal = '无'
        //   form.reviewOnxuans = this.state.datas.ReviewOn
        //   this.props.form.setFieldsValue({
        //     contract: this.state.form.contracts + '-' + (Number(array[array.length - 1].Title) + 1), //编号
        //     theContract: this.state.datas.RegulationsName,//名称
        //     qualifications: this.state.datas.ModifyNature,//修改性质
        //     we: this.state.datas.BelongsCompany,//我方
        //     examination: this.state.datas.LawyerReview,//律师审查
        //     reviewOnxuans: this.state.datas.ReviewOn,//审查担当
        //     versionNo: Number(array[array.length - 1].Title) + 1,//版本号
        //     file: this.state.datas.AcceptTime.substring(0, 4) + '/' + this.state.datas.BelongsCompany + '/' + this.state.form.contracts + '-' + (Number(array[array.length - 1].Title) + 1) + '/',//文件保存
        //   })

        //   setTimeout(async () => {
        //     this.Folder(this.state.datas.BelongsCompany, this.state.datas.AcceptTime.substring(0, 4), this.state.form.contracts + '-' + (Number(array[array.length - 1].Title) + 1))
        //     this.setState({
        //       form,
        //       disabled: true,
        //       pidisabled:true,
        //       JudgmentVariable: this.state.wedisabled ? this.state.JudgmentVariable : '有效'
        //     })
        //     let pa = {
        //       Guid: ListGUID.Regulations, //guid 规章
        //       Obj: {
        //         Title: this.state.form.contracts + '-' + (Number(array[array.length - 1].Title) + 1), //编号
        //         RegulationsName: this.state.datas.RegulationsName,//名称
        //         ModifyNature: this.state.datas.ModifyNature,//修改性质
        //         BelongsCompany: this.state.datas.BelongsCompany,//我方
        //         LawyerReview: this.state.datas.LawyerReview,//律师审查
        //         ReviewOn: this.state.datas.ReviewOn,//审查担当
        //         HasReviewOpinion:this.state.form.proposal,//申请书
        //         VersionNum: Number(array[array.length - 1].Title) + 1,//版本号
        //         FileAddress: this.state.datas.AcceptTime.substring(0, 4) + '/' + this.state.datas.BelongsCompany + '/' + this.state.form.contracts + '-' + (Number(array[array.length - 1].Title) + 1) + '/',//文件保存
        //         RegulationsStatus: '有效'
        //       }
        //     }
        //     
        //     var result = await Api._saveaddDataGuid(pa);
        //   }, 100);
        //   return;
        // }
        /** ------------------------------------------ 暂时注释 */
      }
    });
    })
    


  }
  //根据编号获取 数据 更新
  public async getedit(item) {
    // var param = {
    //   Guid: ListGUID.Regulations, //
    //   Filter: `Title eq '${item}'`
    // };
    // let Persons = await Api._getModel(param);
    this.setState({
      loading: true
    })
    let params: any = [
      {
        logic: "and",
        where: [
          {
            key: 'Title',
            filterType: "Eq",
            value: item
          }
        ]
      }
    ];
    let data = await Api._getPaged2({ Guid: ListGUID.Regulations, PageSize: 100000, PageIndex: 1, FilterL: params });
    let Persons = data.data;
    let reviewOnxuan = []
    let reviewOn = []
    if (Persons[0].ReviewOn != null) {
      if (Persons[0].ReviewOn.indexOf(';') != -1) {
        let arrays = Persons[0].ReviewOn.split(';')
        for (let i = 0; arrays.length > i; i++) {
          reviewOnxuan.push(Number(arrays[i].split('#')[0]))
          reviewOn.push(arrays[i].split('#')[1])
        }
      } else {
        reviewOnxuan.push(Number(Persons[0].ReviewOn.split('#')[0]))
        reviewOn.push(Persons[0].ReviewOn.split('#')[1])
      }
    }

    await this.setState({
      form: {
        contract: Persons[0].Title, //合同编号
        date: Persons[0].AcceptTime == null ? null : moment(Persons[0].AcceptTime),
        date1: Persons[0].LastAnswerTime == null ? null : moment(Persons[0].LastAnswerTime),
        language: Persons[0].Language,//语言
        problem: Persons[0].Question,//问题
        nature: Persons[0].RegulationsCatalog,//规定分类
        theContract: Persons[0].RegulationsName,//规定名称
        qualificationss: Persons[0].ModifyNature ? Persons[0].ModifyNature.split(',') : [],//修改性质
        otherSide: Persons[0].RegulationsNum,//规定编号
        examination: Persons[0].LawyerReview,//律师审查 
        we: Persons[0].BelongsCompany, //规定所属公司
        cutNumber: Persons[0].RuleNumber,//决裁编号
        community: Persons[0].RelierName,//社内依赖者
        reviewOnxuans: Persons[0].ReviewOn,//审查担当
        file: Persons[0].FileAddress,//文件保存路径
        other: Persons[0].Other,//其它 
        proposal:Persons[0].HasReviewOpinion,//申请书
        reviewOnxuan: reviewOnxuan,
        reviewOn: reviewOn,
        versionNo: Persons[0].VersionNum
        // enclosurelist: Persons[0].Names == null ? [] : Persons[0].Names.split(';')
      },
      JudgmentVariableID: Persons[0].ID,
      JudgmentVariable: '废弃',
      wedisabled: true,
      disabled: true,
      currentForm: Persons[0],
      loading: false
    })
    await dynamicsService.UpdateListFileNames({dataid: Persons[0].id, listguid: ListGUID.Regulations, fileaddress: Persons[0].FileAddress})
  }
  public prefixZero(n, m) {
    var _a = (Array(m).join('0') + n).slice(-m);
    return _a;
  }
  public async Folder(A, B, C) {
    let Persons2 = await Api.checkAndCreateFolder(`${ListGUID.RegulationsLibRelativeUrl}/${B}`)
    let Persons3 = await Api.checkAndCreateFolder(`${ListGUID.RegulationsLibRelativeUrl}/${B}/${A}`)
    let Persons4 = await Api.checkAndCreateFolder(`${ListGUID.RegulationsLibRelativeUrl}/${B}/${A}/${C}`)
  }
}
export default Form.create()(RegulationsVersion);